#include "SettingWidget.h"
#include "log.h"
#include <QHBoxLayout>
#include <QScreen>
#include <QStackedLayout>
#include <QListWidget>
#include <QGuiApplication>
#include <QVBoxLayout>
#include <QColorDialog>
#include <QMessageBox>
#include <QColor>
#include "qtmaterialtabs.h"
#include "qtmaterialflatbutton.h"
#include "qtmaterialdialog.h"
#include "TimedWidget.h"
#include "ReminderWidget.h"
#include "SystemWidget.h"
#include "ScreenshotSettingsWidget.h"
#include <QStackedWidget>
#include <QScrollArea>
#include <QMetaObject>
#include "ConfigService.h"
constexpr int TITLE_BAR_H = 48;

int SettingWidget::getScreenWidth() const
{
    return m_nScreenWidth;
}

void SettingWidget::setScreenWidth(int width)
{
    m_nScreenWidth=width;
}

int SettingWidget::getScreenHeight() const
{
    return m_nScreenHeigth;
}

void SettingWidget::setScreenHeigth(int heigth)
{
    m_nScreenHeigth=heigth;
}

void SettingWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
}


SettingWidget::SettingWidget(QWidget *parent)
    :FramelessWindow(parent)
    ,nRet(0)
{
    setWindowStyle();

    initForm();

    setupForm();

    setTitlebarWidgets({titleWidget, lblIcon, lblTitle});

    connectFunction();
}

SettingWidget::~SettingWidget()
{
}

void SettingWidget::connectFunction()
{
    // 关联信号槽
    connect(btnClose, &QPushButton::clicked, [this]() { this->close(); });

    connect(btnMax, &QPushButton::clicked,
            [this]()
            {
                // 切换最大化/正常显示
                this->setWindowState(this->windowState().testFlag(Qt::WindowNoState) ? Qt::WindowMaximized : Qt::WindowNoState);
            });

    connect(btnMin, &QPushButton::clicked,
            [this]()
            {
                // 使用下面的与或非写法，不要改变原来的状态。
                this->setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
            });

}

void SettingWidget::setupForm()
{
    // 创建三个界面
    TimedWidget *timedWidget = new TimedWidget(m_nScreenWidth,m_nScreenHeigth,mainWidget);
    timedWidget->setFormSize(m_nScreenWidth,m_nScreenHeigth);
    connect(timedWidget,&TimedWidget::sigClose,this,[this](){close();});
    
    // 隐藏TimedWidget内部的按钮（现在由外层统一管理）
    if (QPushButton* btn = timedWidget->findChild<QPushButton*>("btnSpecialCount")) btn->hide();
    if (QPushButton* btn = timedWidget->findChild<QPushButton*>("btnHelp")) btn->hide();
    if (QPushButton* btn = timedWidget->findChild<QPushButton*>("btnApply")) btn->hide();
    if (QPushButton* btn = timedWidget->findChild<QPushButton*>("btnClose")) btn->hide();
    // 隐藏按钮所在的布局（如果有独立的按钮栏容器）
    QList<QHBoxLayout*> hboxes = timedWidget->findChildren<QHBoxLayout*>();
    for (QHBoxLayout* hbox : hboxes) {
        // 检查布局是否包含按钮（通过按钮数量判断）
        int buttonCount = 0;
        for (int i = 0; i < hbox->count(); ++i) {
            if (qobject_cast<QPushButton*>(hbox->itemAt(i)->widget())) {
                buttonCount++;
            }
        }
        // 如果布局主要是按钮（>=3个），则隐藏整个布局
        if (buttonCount >= 3) {
            for (int i = 0; i < hbox->count(); ++i) {
                if (QWidget* w = hbox->itemAt(i)->widget()) {
                    w->hide();
                }
            }
        }
    }
    ReminderWidget *reminderWidget = new ReminderWidget(mainWidget);
    connect(reminderWidget,&ReminderWidget::sigClose,this,[this](){close();});
    // 隐藏ReminderWidget的按钮（特定计时、帮助、应用、关闭）
    for (QPushButton* btn : reminderWidget->findChildren<QPushButton*>()) {
        if (btn->text().contains("特定") || btn->text().contains("帮助") || 
            btn->text().contains("应用") || btn->text().contains("关闭")) {
            btn->hide();
        }
    }
    
    SystemWidget *systemWidget = new SystemWidget(mainWidget);
    connect(systemWidget,&SystemWidget::sigClose,this,[this](){close();});
    // 隐藏SystemWidget的按钮（恢复默认、应用、关闭）
    for (QPushButton* btn : systemWidget->findChildren<QPushButton*>()) {
        if (btn->text().contains("恢复") || btn->text().contains("默认") ||
            btn->text().contains("应用") || btn->text().contains("关闭")) {
            btn->hide();
        }
    }
    connect(systemWidget,&SystemWidget::sigFontChanged,this,[this](){
        // ✅ 字体改变时，通过ConfigService通知主窗口更新
        ConfigService::instance().saveConfig();
    });
    connect(systemWidget,&SystemWidget::sigLanguageChanged,this,[this](){
        // 语言改变时，可以在这里重新加载翻译
        QMessageBox::information(this, "提示", "语言设置已保存，重启应用程序后生效。");
    });

    QtMaterialTabs      *const  m_tabs  =   new QtMaterialTabs(mainWidget);
    m_tabs->setUseThemeColors(false);
    m_tabs->setInkColor(QColor(76, 175, 80)); // 绿色 #4CAF50
    m_tabs->setTextColor(QColor(224, 224, 224)); // 浅灰色 #E0E0E0
    m_tabs->setBackgroundColor(QColor(48, 48, 50)); // 深灰色 #303032
    
    // 创建QStackedWidget，用于切换显示的界面
    QStackedWidget *stackedWidget = new QStackedWidget(this);
    
    // 辅助lambda：将widget包裹在ScrollArea + 固定底部按钮栏的容器中
    auto wrapWithFixedButtons = [this](QWidget* contentWidget, const QString& tabName) -> QWidget* {
        // 创建外层容器（上下分割：滚动内容 + 固定按钮）
        QWidget* tabContainer = new QWidget();
        QVBoxLayout* tabLayout = new QVBoxLayout(tabContainer);
        tabLayout->setContentsMargins(0, 0, 0, 0);
        tabLayout->setSpacing(0);
        
        // === 上部：滚动内容区域 ===
        QWidget* contentContainer = new QWidget();
        contentContainer->setStyleSheet("background: transparent;");
        QVBoxLayout* contentLayout = new QVBoxLayout(contentContainer);
        contentLayout->setContentsMargins(16, 16, 16, 16);
        contentLayout->setSpacing(0);
        contentLayout->addWidget(contentWidget);
        
        QScrollArea* scrollArea = new QScrollArea();
        scrollArea->setWidget(contentContainer);
        scrollArea->setWidgetResizable(true);
        scrollArea->setFrameShape(QFrame::NoFrame);
        scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        scrollArea->setStyleSheet(R"(
            QScrollArea {
                background: transparent;
                border: none;
            }
            QScrollBar:vertical {
                background: #2C2C2E;
                width: 12px;
                margin: 0px;
            }
            QScrollBar::handle:vertical {
                background: #5A5A5C;
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: #6A6A6C;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                height: 0px;
            }
            QScrollBar:horizontal {
                background: #2C2C2E;
                height: 12px;
                margin: 0px;
            }
            QScrollBar::handle:horizontal {
                background: #5A5A5C;
                border-radius: 6px;
                min-width: 20px;
            }
            QScrollBar::handle:horizontal:hover {
                background: #6A6A6C;
            }
            QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {
                width: 0px;
            }
        )");
        
        tabLayout->addWidget(scrollArea, 1); // 拉伸占据剩余空间
        
        // === 下部：固定按钮栏 ===
        QWidget* buttonBar = new QWidget();
        buttonBar->setStyleSheet(R"(
            QWidget {
                background: #3C3C3E;
                border-top: 1px solid #555;
            }
        )");
        QHBoxLayout* buttonLayout = new QHBoxLayout(buttonBar);
        buttonLayout->setContentsMargins(16, 12, 16, 12);
        buttonLayout->setSpacing(8);
        
        // 根据Tab类型添加特定按钮
        if (tabName == "限时" || tabName == "提醒") {
            QPushButton* btnSpecial = new QPushButton("特定计时");
            btnSpecial->setProperty("styleClass", "secondary");
            // 连接到内部按钮
            connect(btnSpecial, &QPushButton::clicked, [contentWidget, tabName]() {
                if (tabName == "限时") {
                    if (TimedWidget* tw = qobject_cast<TimedWidget*>(contentWidget)) {
                        if (QPushButton* originalBtn = tw->findChild<QPushButton*>("btnSpecialCount")) {
                            originalBtn->click();
                        }
                    }
                } else if (tabName == "提醒") {
                    if (ReminderWidget* rw = qobject_cast<ReminderWidget*>(contentWidget)) {
                        // 查找ReminderWidget的btnSpecialCount
                        for (QPushButton* btn : rw->findChildren<QPushButton*>()) {
                            if (btn->text().contains("特定")) {
                                btn->click();
                                break;
                            }
                        }
                    }
                }
            });
            buttonLayout->addWidget(btnSpecial);
            
            QPushButton* btnHelp = new QPushButton("帮助");
            btnHelp->setProperty("styleClass", "secondary");
            connect(btnHelp, &QPushButton::clicked, [contentWidget, tabName]() {
                if (tabName == "限时") {
                    if (TimedWidget* tw = qobject_cast<TimedWidget*>(contentWidget)) {
                        if (QPushButton* originalBtn = tw->findChild<QPushButton*>("btnHelp")) {
                            originalBtn->click();
                        }
                    }
                } else if (tabName == "提醒") {
                    if (ReminderWidget* rw = qobject_cast<ReminderWidget*>(contentWidget)) {
                        // 查找ReminderWidget的btnHelp
                        for (QPushButton* btn : rw->findChildren<QPushButton*>()) {
                            if (btn->text().contains("帮助")) {
                                btn->click();
                                break;
                            }
                        }
                    }
                }
            });
            buttonLayout->addWidget(btnHelp);
        } else if (tabName == "系统") {
            QPushButton* btnReset = new QPushButton("恢复默认");
            btnReset->setProperty("styleClass", "secondary");
            connect(btnReset, &QPushButton::clicked, [contentWidget]() {
                if (SystemWidget* sw = qobject_cast<SystemWidget*>(contentWidget)) {
                    // 调用SystemWidget的onResetToDefault槽函数
                    QMetaObject::invokeMethod(sw, "onResetToDefault");
                }
            });
            buttonLayout->addWidget(btnReset);
        }
        
        buttonLayout->addStretch(); // 弹簧，将后续按钮推到右侧
        
        // 通用按钮：应用、关闭
        QPushButton* btnApply = new QPushButton("应用");
        btnApply->setProperty("styleClass", "primary");
        btnApply->setMinimumWidth(80);
        connect(btnApply, &QPushButton::clicked, [contentWidget, tabName]() {
            // 触发内容widget的保存逻辑
            if (tabName == "限时") {
                if (TimedWidget* tw = qobject_cast<TimedWidget*>(contentWidget)) {
                    QMetaObject::invokeMethod(tw, "onSaveDataBtn");
                }
            } else if (tabName == "提醒") {
                if (ReminderWidget* rw = qobject_cast<ReminderWidget*>(contentWidget)) {
                    QMetaObject::invokeMethod(rw, "onSaveDataBtn");
                }
            } else if (tabName == "系统") {
                if (SystemWidget* sw = qobject_cast<SystemWidget*>(contentWidget)) {
                    QMetaObject::invokeMethod(sw, "onSaveDataBtn");
                }
            } else if (tabName == "截图") {
                if (ScreenshotSettingsWidget* ssw = qobject_cast<ScreenshotSettingsWidget*>(contentWidget)) {
                    QMetaObject::invokeMethod(ssw, "onApply");
                }
            }
        });
        buttonLayout->addWidget(btnApply);
        
        QPushButton* btnClose = new QPushButton("关闭");
        btnClose->setProperty("styleClass", "secondary");
        btnClose->setMinimumWidth(80);
        connect(btnClose, &QPushButton::clicked, this, [this]() { close(); });
        buttonLayout->addWidget(btnClose);
        
        tabLayout->addWidget(buttonBar); // 固定在底部
        
        return tabContainer;
    };
    
    auto* screenshotSettings = new ScreenshotSettingsWidget(mainWidget);
    // 隐藏ScreenshotSettingsWidget的按钮（如果有）
    for (QPushButton* btn : screenshotSettings->findChildren<QPushButton*>()) {
        if (btn->text().contains("应用") || btn->text().contains("关闭") || 
            btn->text().contains("Apply") || btn->text().contains("Close")) {
            btn->hide();
        }
    }
    
    // 为每个Tab添加固定底部按钮的布局
    stackedWidget->addWidget(wrapWithFixedButtons(timedWidget, "限时"));       // 添加"限时"界面
    stackedWidget->addWidget(wrapWithFixedButtons(reminderWidget, "提醒"));    // 添加"提醒"界面
    stackedWidget->addWidget(wrapWithFixedButtons(systemWidget, "系统"));      // 添加"系统"界面
    stackedWidget->addWidget(wrapWithFixedButtons(screenshotSettings, "截图")); // 添加"截图"界面
// 显示全屏窗口
    //showFullScreen();
    // mainLayout在第301行创建时已经指定了mainWidget为父对象，不需要再次setLayout
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    mainLayout->setContentsMargins(0, 0, 0, 0);
#else
    mainLayout->setMargin(0);
#endif
    mainLayout->setSpacing(0);
    
    m_tabs->addTab("限时");
    m_tabs->addTab("提醒");
    m_tabs->addTab("系统");
    m_tabs->addTab("截图");

    // 在Tab切换时更新QStackedWidget显示内容
    connect(m_tabs, &QtMaterialTabs::currentChanged, [=](int index) {
        stackedWidget->setCurrentIndex(index);
    });

    // 设置QStackedWidget样式（边距由各ScrollArea内部处理）
    stackedWidget->setStyleSheet(R"(
        QStackedWidget {
            background: #2C2C2E;
            border: none;
        }
    )");
    
    mainLayout->addWidget(m_tabs);
    mainLayout->addWidget(stackedWidget, 1); // 让stackedWidget占据剩余空间
}

void SettingWidget::changeEvent(QEvent *event)
{
    if ( event->type() == QEvent::WindowStateChange ) {
        if ( this->windowState().testFlag(Qt::WindowMaximized) ) {
            btnMax->setStyleSheet(R"(
                QPushButton {
                    background-image: url(:/resource/svg/maximize_20_max.svg);
                    border: none;
                    background-repeat: none;
                    background-position: center;
                    border-radius: 4px;
                }
                QPushButton:hover {
                    background-color: #565656;
                }
            )");
        } else if ( this->windowState().testFlag(Qt::WindowNoState) ) {
            btnMax->setStyleSheet(R"(
                QPushButton {
                    background-image: url(:/resource/svg/maximize_20_normal.svg);
                    border: none;
                    background-repeat: none;
                    background-position: center;
                    border-radius: 4px;
                }
                QPushButton:hover {
                    background-color: #565656;
                }
            )");
        }
    }
}

void SettingWidget::initForm()
{
    // 1.3 窗体整体采用垂直布局
    QVBoxLayout* vl = new QVBoxLayout(this);
    vl->setSpacing(0);
    vl->setContentsMargins(0, 0, 0, 0);

    // 1.4 并嵌套一层QWidget，添加阴影效果
    QWidget* frameWidget = new QWidget(this);
    frameWidget->setObjectName("frameWidget");
    vl->addWidget(frameWidget);

    // 1.5 嵌套的QWidget同样采用垂直布局
    QVBoxLayout* layout = new QVBoxLayout(frameWidget);
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);

    // 2. 标题栏
    // 2.1 设置固定高度、背景色
    titleWidget = new QWidget(this);
    titleWidget->setFixedHeight(TITLE_BAR_H);
    titleWidget->setStyleSheet(R"(
        background-color: #3C3C3E;
        border-bottom: 1px solid #555;
    )");

    // 2.2 标题栏采用水平布局
    QHBoxLayout* titleLayout = new QHBoxLayout(titleWidget);  // 标题栏采用水平布局
    titleLayout->setContentsMargins(8, 8, 8, 8);              // 这里必须设置一个间距
    titleLayout->setSpacing(0);

    // 2.3 把标题栏添加到整体窗体布局中。之后就可以向titleLayout中添加控件了
    layout->addWidget(titleWidget);

    // 2.4 添加图标
    lblIcon = new QLabel(this);
    lblIcon->setFixedSize(20, 20);
    lblIcon->setStyleSheet("background-image:url(:/resource/svg/setting.svg);border:none");
    titleLayout->addWidget(lblIcon);

    // 2.5 添加弹簧: 在图标和标题之间增加间距
    QSpacerItem* space = new QSpacerItem(6, 20, QSizePolicy::Fixed, QSizePolicy::Fixed);
    titleLayout->addSpacerItem(space);

    // 2.6 添加标题
    lblTitle = new QLabel(this);

    lblTitle->setText("设置");

    lblTitle->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    lblTitle->setStyleSheet(R"(
            background-color: transparent;
            font: 18px "Microsoft YaHei";
            font-weight: bold;
            color: #E0E0E0;
            border: none;
        )");
    titleLayout->addWidget(lblTitle);

    // 2.7 添加最小化按钮
    btnMin = new QPushButton(this);
    btnMin->setCursor(QCursor(Qt::PointingHandCursor));
    btnMin->setStyleSheet(R"(
            QPushButton {
                background-image: url(:/resource/svg/minimize_20.svg);
                border: none;
                background-repeat: none;
                background-position: center;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #565656;
            }
        )");
    btnMin->setFixedSize(36, 32);
    titleLayout->addWidget(btnMin);

    // 2.8 添加最大化按钮
    btnMax = new QPushButton(this);
    btnMax->setCursor(QCursor(Qt::PointingHandCursor));
    btnMax->setStyleSheet(R"(
            QPushButton {
                background-image: url(:/resource/svg/maximize_20_normal.svg);
                border: none;
                background-repeat: none;
                background-position: center;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #565656;
            }
        )");
    btnMax->setFixedSize(36, 32);
    titleLayout->addWidget(btnMax);

    // 2.9 添加关闭按钮
    btnClose = new QPushButton(this);
    btnClose->setCursor(QCursor(Qt::PointingHandCursor));
    btnClose->setStyleSheet(R"(
            QPushButton {
                background-image: url(:/resource/svg/close_20.svg);
                border: none;
                background-repeat: none;
                background-position: center;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #DE061A;
            }
        )");
    btnClose->setFixedSize(36, 32);
    titleLayout->addWidget(btnClose);

    // 3. 主体
    // 3.1 设置背景色
    mainWidget = new QWidget(this);
    mainWidget->setStyleSheet(R"(
        color: #E0E0E0;
        background: #2C2C2E;
    )");  // 设置背景颜色

    // 3.2 标题栏采用水平布局
    mainLayout = new QVBoxLayout(mainWidget);
    mainLayout->setSpacing(0);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // 3.3 把主体添加到整体窗体布局中。之后就可以向mainLayout中添加控件了
    layout->addWidget(mainWidget);  // 将主体添加到布局中
}

void SettingWidget::setWindowStyle()
{
    // 获取主显示器对象
    QScreen* screen = QGuiApplication::primaryScreen();

    // 获取主显示器的大小并将窗口大小设置为该大小
    setScreenWidth(screen->availableSize().width()*0.45);
    setScreenHeigth(screen->availableSize().height()*0.8); // 提高至80%以容纳更多内容

    setMinimumSize(600, 500); // 设置最小尺寸
    setMaximumSize(m_nScreenWidth, m_nScreenHeigth); // 设置最大尺寸（高度已包含标题栏）

    resize(m_nScreenWidth, m_nScreenHeigth);// 设置窗口大小
    
    // 设置整体样式
    setStyleSheet(R"(
        QWidget {
            font-family: "Microsoft YaHei", "Segoe UI", sans-serif;
        }
    )");
}
